'use strict'
const path = require('path')
const CompressionPlugin = require('compression-webpack-plugin')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = process.env.VUE_APP_TITLE || 'ASL'
const port = process.env.port || process.env.npm_config_port || 80

module.exports = {
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  transpileDependencies: ['quill'],

  devServer: {
    host: '0.0.0.0',
    port: port,
    open: true,
    hot: true,  // 启用热更新
    compress: true,  // 启用gzip压缩
    headers: {
      'Access-Control-Allow-Origin': '*'  // 允许跨域
    },
    proxy: {
      [process.env.VUE_APP_BASE_API]: {
        target: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      },
      '^/v3/api-docs/(.*)': {
        target: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080',
        changeOrigin: false
      }
    }
  },

  css: {
    extract: true,  // 生产环境提取CSS
    sourceMap: false,
    loaderOptions: {
      sass: {
        sassOptions: {
          outputStyle: 'compressed'  // 压缩CSS输出
        }
      }
    }
  },

  configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src'),
        'vue$': 'vue/dist/vue.runtime.esm.js'  // 使用运行时构建版本
      }
    },
    performance: {
      hints: false,  // 关闭性能提示
      maxEntrypointSize: 512000,
      maxAssetSize: 512000
    },
    plugins: [
      new CompressionPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.(js|css|html|json|svg)(\?.*)?$/i,
        threshold: 10240,  // 超过10KB压缩
        minRatio: 0.8,
        deleteOriginalAssets: false
      })
    ]
  },

  chainWebpack(config) {
    // 移除预加载和预取
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')

    // SVG Sprite 优化
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()

    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({ symbolId: 'icon-[name]' })

    // 生产环境优化
    config.when(process.env.NODE_ENV !== 'development', config => {
      config.optimization
        .minimize(true)
        .minimizer('terser')
        .tap(args => {
          args[0].terserOptions.compress.drop_console = true
          args[0].terserOptions.output = {
            comments: false
          }
          return args
        })

      config.optimization.splitChunks({
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 20000,  // 更小的代码分割阈值
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial'
          },
          elementUI: {
            name: 'chunk-elementUI',
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
            priority: 20
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'),
            minChunks: 2,  // 降低公共组件复用次数阈值
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })

      config.optimization.runtimeChunk('single')

      // 添加文件指纹
      config.output
        .filename('static/js/[name].[contenthash:8].js')
        .chunkFilename('static/js/[name].[contenthash:8].js')
    })
  }
}
